import React from 'react';
import {connect} from 'dva';
import {Form, Row, Col, DatePicker, Table, Input, Button, Select, message} from 'antd';
import Constants from "../../../utils/Constants";

const dateFormat = "YYYY-MM-DD";
const {RangePicker} = DatePicker;
const FormItem = Form.Item;
const R = require("ramda");

const orderBenefit = Form.create()(class OrderBenefit extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.dispatch({type: 'orderbenefitReport/queryOrderBenefit', payload: {page: Constants.DEFAULT_PAGE}});
    }

    columns = [
        {title: "客户名称", dataIndex: 'cstName', key: 'cstName'},
        {title: "合同协议号", dataIndex: 'contractNo', key: 'contractNo'},
        {title: "报关金额", dataIndex: 'orderAmount', key: 'orderAmount'},
        {title: "报关币种", dataIndex: 'currency', key: 'currency'},
        {title: "计费方式", dataIndex: 'agencyType', key: 'agencyType'},
        {title: "手续费率", dataIndex: 'feeRate', key: 'feeRate'},
        {title: "垫资金额", dataIndex: 'taxRefund', key: 'taxRefund'},
        {title: "资金成本", dataIndex: 'fundCost', key: 'fundCost'},
        {title: "手续费", dataIndex: 'agencyFee', key: 'agencyFee'},
        {title: "本地费利润", dataIndex: 'feeBenefit', key: 'feeBenefit'},
        {title: "订单毛利", dataIndex: 'finalBenefit', key: 'finalBenefit'},
        {title: "提交时间", dataIndex: 'submitTime', key: 'submitTime'}
    ];


    handleSearch = (flag) => {
        let values = this.props.form.getFieldsValue();
        let newPage = this.props.orderbenefitReport.page;
        if (flag) newPage.page = 1;

        let times = values.timeRange;
        if (values.isCost === "1" && (!values.days || !values.percent)) {
            message.error("请输入周转天数和年化利率!");
            return;
        }

        values.isCost === '1' ? values.isCost = true : values.isCost = false;
        this.props.dispatch({
            type: "orderbenefitReport/queryOrderBenefit",
            payload: {
                beginDate: R.isNil(times) || R.isEmpty(times) ? null : times[0].format(dateFormat),
                endDate: R.isNil(times) || R.isEmpty(times) ? null : times[1].format(dateFormat),
                ...values,
                page: newPage
            }
        })
    }


    handleExport = () => {
        let values = this.props.form.getFieldsValue();
        let times = values.timeRange;
        this.props.dispatch({
            type: "orderbenefitReport/generateOrderBenefit",
            payload: {
                beginTime: R.isNil(times) || R.isEmpty(times) ? null : times[0].format(dateFormat),
                endTime: R.isNil(times) || R.isEmpty(times) ? null : times[1].format(dateFormat),
                ...values
            }
        })
    }


    render() {
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.orderbenefitReport.page.size,
            total: this.props.orderbenefitReport.page.totalRow,
            showSizeChanger: true,
            current: this.props.orderbenefitReport.page.page,
            onShowSizeChange: (current, size) => {
                let values = this.props.form.getFieldsValue();
                let times = values.timeRange;
                let newPage = this.props.orderbenefitReport.page;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'orderbenefitReport/queryOrderBenefit',
                    payload: {
                        beginTime: R.isNil(times) || R.isEmpty(times) ? null : times[0].format(dateFormat),
                        endTime: R.isNil(times) || R.isEmpty(times) ? null : times[1].format(dateFormat),
                        ...values,
                        page: newPage,
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let values = this.props.form.getFieldsValue();
                let times = values.timeRange;
                let newPage = this.props.orderbenefitReport.page;
                newPage.page = pageNumber;
                newPage.pageSize = pageSize;
                this.props.dispatch({
                    type: 'orderbenefitReport/queryOrderBenefit',
                    payload: {
                        beginTime: R.isNil(times) || R.isEmpty(times) ? null : times[0].format(dateFormat),
                        endTime: R.isNil(times) || R.isEmpty(times) ? null : times[1].format(dateFormat),
                        ...values,
                        page: newPage,
                    }
                });
            }
        };


        const {getFieldDecorator} = this.props.form;
        let formItemLayout = {labelCol: {span: 6}, wrapperCol: {span: 18}};
        let dataSource = R.isNil(this.props.orderbenefitReport.list) ? null : this.props.orderbenefitReport.list;
        return (
            <Form>
                <Row>
                    <Col span={6}><FormItem {...formItemLayout} label={'合同协议号'}>{getFieldDecorator('contractNo')(<Input
                        style={{width: '90%'}}/>)}</FormItem></Col>
                    <Col span={6}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('cstName')(<Input
                        style={{width: '90%'}}/>)}</FormItem></Col>
                    <Col span={2}>
                        <Button type="primary" icon="search" style={{marginLeft: 10}}
                                onClick={this.handleSearch.bind(this, true)}>查询</Button>
                    </Col>
                    <Col span={2}>
                        <Button type="primary" onClick={this.handleExport.bind(this)}>导出数据</Button>
                    </Col>
                </Row>
                <Row>
                    <Col span={6}>
                        <FormItem {...formItemLayout} label={'资金成本'}>{getFieldDecorator('isCost')(
                            <Select style={{width: '90%'}} size={'default'} allowClear>
                                <Select.Option value="1">是</Select.Option>
                                <Select.Option value="0">否</Select.Option>
                            </Select>
                        )}
                        </FormItem>
                    </Col>
                    <Col span={6}>
                        <FormItem {...formItemLayout} label="提交时间">
                            {getFieldDecorator("timeRange", {
                                initialValue: null,
                            })(
                                <RangePicker
                                    style={{width: '90%'}}
                                    showTime={{format: 'YYYY-MM-DD'}}
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                />
                            )
                            }
                        </FormItem>
                    </Col>
                </Row>
                {this.props.form.getFieldValue('isCost') && (this.props.form.getFieldValue('isCost').includes('1')) ?
                    <Row>
                        <Col span={6}><FormItem {...formItemLayout} label={'周转天数'}>{getFieldDecorator('days')(<Input
                            placeholder="按退税级别，C类：90天" style={{width: '90%'}}/>)}</FormItem></Col>
                        <Col span={6}><FormItem {...formItemLayout} label={'年化利率(%)'}>{getFieldDecorator('percent')(<Input
                            style={{width: '90%'}}/>)}</FormItem></Col>
                    </Row>
                    : ""
                }
                <Row>
                    <Table rowKey='contractNo' dataSource={dataSource} loading={this.props.loading} pagination={pagination} size={'middle'} columns={this.columns} bordered={true}/>
                </Row>

            </Form>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.orderbenefitReport, orderbenefitReport: state.orderbenefitReport
    };
}

export default connect(mapStateToProps)(orderBenefit);

